package com.example.mallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.common.utils.R;
import com.es.vo.SkuESModel;
import com.example.mallproduct.controller.vo.OrderItemSpuInfoVO;
import com.example.mallproduct.dao.SpuInfoDao;
import com.example.mallproduct.entity.BrandEntity;
import com.example.mallproduct.entity.CategoryEntity;
import com.example.mallproduct.entity.ProductAttrValueEntity;
import com.example.mallproduct.entity.SkuInfoEntity;
import com.example.mallproduct.entity.SpuInfoDescEntity;
import com.example.mallproduct.entity.SpuInfoEntity;
import com.example.mallproduct.fegin.EsFeginService;
import com.example.mallproduct.fegin.WareFeginService;
import com.example.mallproduct.service.AttrService;
import com.example.mallproduct.service.BrandService;
import com.example.mallproduct.service.CategoryService;
import com.example.mallproduct.service.ProductAttrValueService;
import com.example.mallproduct.service.SkuInfoService;
import com.example.mallproduct.service.SkuSaleAttrValueService;
import com.example.mallproduct.service.SpuInfoDescService;
import com.example.mallproduct.service.SpuInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;

    /**
     * SPU信息检索
     * 分页查询
     * 分类 品牌 状态 关键字查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 设置对应的检索条件
        // 1. 关键字查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            // 需要添加关键字查询
            wrapper.and((w) -> {
                w.eq("id", key)
                        .or().like("spu_name", key)
                        .or().like("spu_description", key);
            });
        }
        // status
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        // catalogId
        String catalogId = (String) params.get("catalogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }
        // brandId
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        page.setRecords(page.getRecords().stream().map(spuInfoEntity -> {
            CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());
            BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
            SpuInfoEntity spuInfo = new SpuInfoEntity();
            BeanUtils.copyProperties(spuInfoEntity, spuInfo);
            spuInfo.setCatalogName(categoryEntity.getName());
            spuInfo.setBrandName(brandEntity.getName());
            return spuInfo;
        }).collect(Collectors.toList()));
        return new PageUtils(page);
    }

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private EsFeginService esFeginService;
    @Autowired
    private SpuInfoService spuInfoService;
    @Autowired
    private SpuInfoDao spuInfoDao;

    /**
     * 商品上架
     * 1 根据spuId查询出相关sku信息 sku_info
     * 2 封装数据存于es
     * 3 更新状态为上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
//        spuid查询sku信息 sku-info
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.skuInfoBySpuId(spuId);

//        spuid查询规格参数
        List<SkuESModel.Attrs> attrsList = this.getAttrsData(spuId);

//        查询是否存在库存
//        根据skuid查询库存
        List<Long> skuIds = skuInfoEntityList.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());
        Map<Long, Boolean> skusHasStockMap = getSkusHasStock(skuIds);

//        封装并存储es

        // 2.远程调用mall-search的服务，将SukESModel中的数据存储到ES中
        List<SkuESModel> skuESModels = skuInfoEntityList.stream().map(item -> {
            SkuESModel model = new SkuESModel();
            // 先实现属性的复制
            BeanUtils.copyProperties(item,model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            // hasStock 是否有库存 --》 库存系统查询  一次远程调用获取所有的skuId对应的库存信息
            if(skusHasStockMap == null){
                model.setHasStock(true);
            }else{
                model.setHasStock(skusHasStockMap.get(item.getSkuId()));
            }
            // hotScore 热度分 --> 默认给0即可
            model.setHotScore(0L);
            // 品牌和类型的名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            model.setCatalogName(category.getName());
            // 需要存储的规格数据
            model.setAttrs(attrsList);

            return model;
        }).collect(Collectors.toList());

        // 将SkuESModel中的数据存储到ES中
        R r = esFeginService.upProduct(skuESModels);
        // 3.更新SPUID对应的状态
        // 根据对应的状态更新商品的状态
        System.out.println("-------------->"+r.getCode());
        if(r.getCode() == 0){
            // 远程调用成功  更新商品的状态为 上架
            spuInfoDao.updateStatus(spuId,"1");
        }else{
            // 远程调用失败
        }

    }

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;

    /**
     * 获取规格参数和值
     *
     * @param spuId
     * @return
     */
    List<SkuESModel.Attrs> getAttrsData(Long spuId) {
        //查询规格参数
        List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<SkuESModel.Attrs> attrsList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productAttrValueEntityList)) {
            //查询可检索的属性
            List<Long> attrIdList = attrService.searchAttr(productAttrValueEntityList.stream().map(item -> item.getAttrId()).collect(Collectors.toList()));
            attrsList = productAttrValueEntityList.stream().filter(item -> attrIdList.contains(item.getAttrId())).map(item -> {
                SkuESModel.Attrs attrs = new SkuESModel.Attrs();
                attrs.setAttrId(item.getAttrId());
                attrs.setAttrName(item.getAttrName());
                attrs.setAttrValue(item.getAttrValue());
                return attrs;
            }).collect(Collectors.toList());

        }
        return attrsList;

    }

    @Autowired
    private WareFeginService wareFeginService;

    private Map<Long,Boolean> getSkusHasStock(List<Long> skuIds){
        return wareFeginService.findBySkuId(skuIds);
    }


    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Override
    public List<OrderItemSpuInfoVO> getOrderItemSpuInfoBySpuId(Long[] spuIds) {
        List<OrderItemSpuInfoVO> list = new ArrayList<>();
        for (Long spuId : spuIds) {
            OrderItemSpuInfoVO vo = new OrderItemSpuInfoVO();
            SpuInfoEntity spuInfoEntity = this.getById(spuId);
            vo.setId(spuId);
            vo.setSpuName(spuInfoEntity.getSpuName());
            vo.setBrandId(spuInfoEntity.getBrandId());
            vo.setCatalogId(spuInfoEntity.getCatalogId());
            // 根据品牌编号查询品牌信息
            BrandEntity brand = brandService.getById(spuInfoEntity.getBrandId());
            vo.setBrandName(brand.getName());
            CategoryEntity category = categoryService.getById(spuInfoEntity.getCatalogId());
            vo.setCatalogName(category.getName());
            // 获取SPU的图片
            SpuInfoDescEntity descEntity = spuInfoDescService.getById(spuId);
            vo.setImg(descEntity.getDecript());
            list.add(vo);
        }
        // 根据SPUID查询出相关的信息
        return list;
    }
}